package cn.lanqiao.springboot.util;


import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

@Component
public class EmailSenderUtil {

    @Autowired
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.key}")
    String key;

    public void sendEmail(String toMail) {
        try {
            //使用des加密生成激活码，加密内容为 toMail+now
            String activCode = DesUtil.encrypt(toMail,key);
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            //是否发送的邮件是富文本（附件，图片，html等）
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);
            messageHelper.setFrom("3208711@qq.com");
            messageHelper.setTo(toMail);
            messageHelper.setSubject("激活邮件-测试");
            //若设置false,则显示原始html代码,无效果
            messageHelper.setText(
                    "<p>\n" +
                            "  <b>" + toMail + "</b>, 您好!\n" +
                            "</p>\n" +
                            "<p>这是一封激活邮件, " +
                            "<a href=\"http://localhost:8080/user/activation/"+activCode+"\">请点击</a>" +
                            "激活您的账号!</p>", true);

            //发送邮件
            javaMailSender.send(mimeMessage);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}
